
package com.yyh.zhujie;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

public class Test2 {
    public static void main(String[] args) throws IOException, ParseException, ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //创建集合
        List<Student1> list = new ArrayList<Student1>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //添加元素
        list.add(new Student1("08001", 32, "0800101", "赵明", sdf.parse("1985-12-23")));
        list.add(new Student1("08002", 28, "0800201", "胡广飞", sdf.parse("1985-10-05")));
        //生成xml文件
        StringBuilder xml = new StringBuilder();
        xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xml.append("<students>\n");
        for (Student1 student1 : list) {
            xml.append("  <student>\n");
            xml.append("    <classId>" + student1.getClassId() + "</classId>\n");
            xml.append("    <stuCount>" + student1.getStuCount() + "</stuCount>\n");
            xml.append("    <stuId>" + student1.getStuId() + "</stuId>\n");
            xml.append("    <name>" + student1.getName() + "</name>\n");
            xml.append("    <birth>" + sdf.format(student1.getBirth()) + "</birth>\n");
            xml.append("  </student>\n");

        }
        xml.append("</students>");

        //写入xml文件
        try (FileWriter writer = new FileWriter("D:\\ideaproject\\IO-code\\fanshe-code-01\\src\\com\\yyh\\zhujie\\students.xml")) {
            writer.write(xml.toString());
        }
        System.out.println("生成xml文件成功！");

        //读取xml文件并使用反射创建对象
        //读取文件内容
        StringBuilder fileContent = new StringBuilder(); // 使用新的StringBuilder避免数据混淆
        try (BufferedReader reader = new BufferedReader(new FileReader("D:\\ideaproject\\IO-code\\fanshe-code-01\\src\\com\\yyh\\zhujie\\students.xml"))) {
            String line;
            while ((line = reader.readLine()) != null) {
                fileContent.append(line).append("\n");
            }
        }

        //解析xml文件内容
        String[] xmls = fileContent.toString().split("<student>");
        List<Student1> list1 = new ArrayList<Student1>();
        for (int i = 1; i < xmls.length; i++){ // 从索引1开始，跳过第一个不包含student标签的块
            String block = xmls[i];
            Class<?> clazz = Class.forName("com.yyh.zhujie.Student1");
            Student1 studentObj = (Student1) clazz.getDeclaredConstructor().newInstance();
            // 提取各个字段的值并使用反射设置
            String classId = extractValue(block, "classId");
            String stuCountStr = extractValue(block, "stuCount");
            String stuId = extractValue(block, "stuId");
            String name = extractValue(block, "name");
            String birthStr = extractValue(block, "birth");

            // 使用反射设置字段值
            setFieldValue(studentObj, "classId", classId);
            setFieldValue(studentObj, "stuCount", Integer.parseInt(stuCountStr));
            setFieldValue(studentObj, "stuId", stuId);
            setFieldValue(studentObj, "name", name);
            // 修改日期解析部分
            try {
                Date birthDate = sdf.parse(birthStr);
                setFieldValue(studentObj, "birth", birthDate);
            } catch (ParseException e) {
                System.err.println("日期解析失败: " + birthStr + ", 使用当前日期作为默认值");
                setFieldValue(studentObj, "birth", new Date());
            }
            list1.add(studentObj);
        }
        //打印反射创建的对象
        System.out.println("使用反射创建的学生对象");
        for (Student1 student1 : list1) {
            System.out.println(student1);
        }

    }

    private static String extractValue(String block, String fieldName) {
        int startIndex = block.indexOf("<" + fieldName + ">");
        int endIndex = block.indexOf("</" + fieldName + ">");
        if (startIndex != -1 && endIndex != -1) {
            return block.substring(startIndex + fieldName.length() + 2, endIndex).trim();
        }
        return null;
    }

    private static void setFieldValue(Object obj, String fieldName, Object value) throws NoSuchFieldException, IllegalAccessException {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }

}
class Student1 implements Serializable {
    private static final long serialVersionUID = 1L;
    private String classId;
    private int stuCount;
    private String stuId;
    private String name;
    private Date birth;

    public Student1() {
    }

    public Student1(String classId, int stuCount, String stuId, String name, Date birth) {
        this.classId = classId;
        this.stuCount = stuCount;
        this.stuId = stuId;
        this.name = name;
        this.birth = birth;
    }

    public String getClassId() {
        return classId;
    }

    public void setClassId(String classId) {
        this.classId = classId;
    }

    public int getStuCount() {
        return stuCount;
    }

    public void setStuCount(int stuCount) {
        this.stuCount = stuCount;
    }

    public String getStuId() {
        return stuId;
    }

    public void setStuId(String stuId) {
        this.stuId = stuId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student1 student1 = (Student1) o;
        return stuCount == student1.stuCount && Objects.equals(classId, student1.classId) && Objects.equals(stuId, student1.stuId) && Objects.equals(name, student1.name) && Objects.equals(birth, student1.birth);
    }

    @Override
    public int hashCode() {
        return Objects.hash(classId, stuCount, stuId, name, birth);
    }

    @Override
    public String toString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return "Student1{" +
                "classId='" + classId + '\'' +
                ", stuCount=" + stuCount +
                ", stuId='" + stuId + '\'' +
                ", name='" + name + '\'' +
                ", birth=" + (birth != null ? sdf.format(birth) : "null") +
                '}';
    }
}